package com.tmall.wireless.vaf.virtualview.view.page;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.PageSliderProvider;
import com.tmall.wireless.vaf.framework.VafContext;
import com.tmall.wireless.vaf.framework.cm.ContainerService;
import com.tmall.wireless.vaf.virtualview.core.IContainer;
import com.tmall.wireless.vaf.virtualview.core.ViewBase;
import com.tmall.wireless.vaf.virtualview.event.EventData;
import com.tmall.wireless.vaf.virtualview.event.EventManager;

import static com.tmall.wireless.vaf.virtualview.core.ViewBase.TYPE;


public class NewPageSliderProvider extends PageSliderProvider {

    private JSONArray jsonArray;

    protected VafContext mContext;

    protected int mContainerId = ContainerService.CONTAINER_TYPE_NORMAL;

    protected ContainerService mContainerService;

    public NewPageSliderProvider(VafContext context) {
        mContainerService = context.getContainerService();
        mContext = context;
    }

    public void setContainerId(int id) {
        mContainerId = id;
    }

    public void setData(JSONArray jsonArray) {
        this.jsonArray = jsonArray;
        notifyDataChanged();
    }

    @Override
    public int getCount() {
        // return jsonArray != null ? jsonArray.size() : 0;
        return jsonArray != null ? Integer.MAX_VALUE : 0;
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int i) {
        Component component = null;
        // JSONObject obj = jsonArray.getJSONObject(i);
        JSONObject obj = jsonArray.getJSONObject(i % jsonArray.size());
        String type = obj.getString(TYPE);
        component = mContainerService.getContainer(type, mContainerId);

        componentContainer.addComponent(component);
        onBindViewHolder(component, i % jsonArray.size());

        return component;
    }

    private void onBindViewHolder(Component component, int pos) {
        try {
            JSONObject jObj = jsonArray.getJSONObject(pos);

            ViewBase vb = ((IContainer) component).getVirtualView();
            if (null != vb) {
                vb.setVData(jObj);
            }
            if (vb.supportExposure()) {
                mContext.getEventManager().emitEvent(EventManager.TYPE_Exposure, EventData.obtainData(mContext, vb));
            }

            vb.ready();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
        componentContainer.removeComponent((Component) o);
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        return component == o;
    }

}
